import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/models/swiper_data.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:shop/router/router.dart';
import 'package:shop/src/app.dart';
import 'package:shop/util/cart.dart';

import 'package:shop/util/color.dart';
import 'package:shop/views/banner_view.dart';

import 'package:shop/vm/detail_vm.dart';

class DetailPage extends StatefulWidget {
  final String arguments;

  const DetailPage({super.key, required this.arguments});

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  final viewModel = DetailViewModel();

  @override
  void initState() {
    super.initState();

    viewModel.getDetailData(widget.arguments);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<DetailViewModel>.value(
      value: viewModel,
      child: Scaffold(
        backgroundColor: Colors.white,
        extendBodyBehindAppBar: true,
        appBar: AppBar(backgroundColor: Colors.white.withAlpha(0)),
        body: Consumer<DetailViewModel>(builder: (context, value, child) {
          return Column(children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(children: [
                  BannerView(
                    height: 300,
                    bannerList: value.dtailInfo.pics?.map(
                          (element) {
                            final bannerInfo = BannerInfo();
                            bannerInfo.imageSrc = element.picsMid;
                            return bannerInfo;
                          },
                        ).toList() ??
                        [],
                  ),
                  Container(
                    padding: EdgeInsets.all(15),
                    child: Column(
                      spacing: 5,
                      children: [
                        Row(
                          children: [
                            Text(
                              '¥${value.dtailInfo.goodsPrice}',
                              textAlign: TextAlign.left,
                              style: TextStyle(
                                  color: HexColor.fromHex('#C00000'),
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            Expanded(
                                child: Text(
                              style: TextStyle(
                                  fontSize: 16,
                                  color: HexColor.fromHex('#333333')),
                              '${value.dtailInfo.goodsName}',
                            )),
                            SizedBox(width: 15),
                            Container(
                              padding: EdgeInsets.only(left: 10),
                              decoration: BoxDecoration(
                                  border: Border(
                                      left: BorderSide(
                                          color: HexColor.fromHex('#333333'),
                                          width: 0.5))),
                              child: Column(
                                children: [
                                  Icon(
                                    Icons.star,
                                    color: HexColor.fromHex('#333333'),
                                  ),
                                  Text(
                                    '收藏',
                                    style: TextStyle(
                                        color: HexColor.fromHex('#333333')),
                                  )
                                ],
                              ),
                            ),
                          ],
                        ),
                        Row(children: [
                          Text(
                            '快递：免运费',
                            style: TextStyle(
                                fontSize: 14,
                                color: HexColor.fromHex('#333333')),
                          )
                        ])
                      ],
                    ),
                  ),
                  Table(
                    columnWidths: {
                      0: FlexColumnWidth(1),
                      1: FlexColumnWidth(1),
                    },
                    border: TableBorder.all(color: Colors.black, width: 0),
                    children: value.dtailInfo.attrs?.map((element) {
                          return TableRow(
                            children: [
                              TableCell(
                                  child: Padding(
                                padding: EdgeInsets.all(10),
                                child: Text(
                                  element.attrName ?? '',
                                  style: TextStyle(fontSize: 13),
                                ),
                              )),
                              TableCell(
                                  child: Padding(
                                padding: EdgeInsets.all(10),
                                child: Text(
                                  element.attrValue ?? '',
                                  style: TextStyle(fontSize: 13),
                                ),
                              )),
                            ],
                          );
                        }).toList() ??
                        [],
                  ),
                  HtmlWidget(value.dtailInfo.goodsIntroduce ?? ''),
                ]),
              ),
            ),
            Container(
              padding: EdgeInsets.only(
                  left: 10,
                  right: 10,
                  top: 10,
                  bottom: MediaQuery.of(context).padding.bottom + 10),
              color: Colors.white,
              child: Row(
                children: [
                  SizedBox(width: 15),
                  InkWell(
                    onTap: () {},
                    child: Column(
                      children: [
                        Icon(Icons.store),
                        Text(
                          '店铺',
                          style: TextStyle(fontSize: 12),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 25),
                  InkWell(
                    onTap: () {
                      Navigator.popUntil(
                        context,
                        (route) {
                          return route.isFirst;
                        },
                      );
                      final sized =
                          tabbarPagekey.currentState as TabbarPageState;
                      sized.switchTab(2);
                    },
                    child: Column(
                      children: [
                        Icon(Icons.shopping_cart),
                        Text(
                          '购物车',
                          style: TextStyle(fontSize: 12),
                        ),
                      ],
                    ),
                  ),
                  Spacer(),
                  Row(
                    children: [
                      SizedBox(
                        width: 100,
                        height: 40,
                        child: TextButton(
                          style: ButtonStyle(
                              shape: WidgetStateProperty.all(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(20),
                                          bottomLeft: Radius.circular(20)))),
                              backgroundColor: WidgetStateProperty.all(
                                  HexColor.fromHex('#C00000'))),
                          onPressed: () {
                            addGoodsAction();
                          },
                          child: Text(
                            '加入购物车',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 100,
                        height: 40,
                        child: TextButton(
                          style: ButtonStyle(
                              shape: WidgetStateProperty.all(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.only(
                                          topRight: Radius.circular(20),
                                          bottomRight: Radius.circular(20)))),
                              backgroundColor:
                                  WidgetStateProperty.all(Colors.orange)),
                          onPressed: () {},
                          child: Text(
                            '立即购买',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ]);
        }),
      ),
    );
  }

  addGoodsAction() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    final getJson = prefs.getString('carts');
    final shopCart = ShopCart();
    GoodInfo? goodInfo;

    if (getJson != null) {
      shopCart.carts = ShopCart.fromJson(jsonDecode(getJson)).carts;
      goodInfo = shopCart.carts.firstWhere(
        (element) => element.goodsId == int.parse(widget.arguments),
        orElse: () => GoodInfo(),
      );
    } else {
      shopCart.carts = <GoodInfo>[];
      goodInfo = GoodInfo();
    }

    if (goodInfo.goodsId > 0) {
      goodInfo.count = goodInfo.count + 1;
    } else {
      goodInfo.goodsId = viewModel.dtailInfo.goodsId ?? 0;
      goodInfo.goodsName = viewModel.dtailInfo.goodsName ?? '';
      goodInfo.goodsPrice = viewModel.dtailInfo.goodsPrice ?? 0;
      goodInfo.goodsSmallLogo = viewModel.dtailInfo.goodsSmallLogo ?? '';
      goodInfo.count = 1;

      shopCart.addGood(goodInfo);
    }

    Fluttertoast.showToast(
        msg: "加入成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
